package cn.wch.ch934xlib.chip;

import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;

import cn.wch.ch934xlib.utils.FormatUtil;
import cn.wch.ch934xlib.utils.LogUtil;

public class ChipTransferUtil {

    public static int controlIn(UsbDeviceConnection connection, int request, int value, int index, byte[] buffer, int length) {
        return connection.controlTransfer(UsbType.USB_DIR_IN | UsbType.USB_TYPE_VENDOR | UsbType.USB_RECIP_DEVICE, request, value, index, buffer, length, 500);
    }

    public static int cmdOut(UsbDeviceConnection connection, UsbEndpoint mCtrlPointOut, int request, int Addr, int Value){
        if(mCtrlPointOut==null){
            return -1;
        }
        byte[] Cmd=new byte[3];
        Cmd[0]=(byte)request;
        Cmd[1]=(byte)Addr;
        Cmd[2]=(byte)Value;
        LogUtil.d("Ctrl Out："+ FormatUtil.bytesToHexString(Cmd,Cmd.length));
        return connection.bulkTransfer(mCtrlPointOut,Cmd,Cmd.length,500);
    }

    public static int cmdOut(UsbDeviceConnection connection, UsbEndpoint mCtrlPointOut, byte[] buffer){
        if(mCtrlPointOut==null){
            return -1;
        }
        LogUtil.d("Ctrl Out："+ FormatUtil.bytesToHexString(buffer,buffer.length));
        return connection.bulkTransfer(mCtrlPointOut,buffer,buffer.length,500);
    }

    public static final class UsbType {
        public static final int USB_TYPE_VENDOR = (0x02 << 5);
        public static final int USB_RECIP_DEVICE = 0x00;
        public static final int USB_DIR_OUT = 0x00; /* to device */
        public static final int USB_DIR_IN = 0x80; /* to host */
    }

    public static final class UsbCmd {
        public static final int USB_VEN_DEBUG_READ	=0X95;
        public static final int USB_VEN_DEBUG_WRITE	=0X9A;
        public static final int USB_VEN_READ_VER	=0X96;
        public static final int USB_VEN_SET_TYPE	=0X97;
        public static final int USB_VEN_CH438_READ	=0X85;
        public static final int USB_VEN_CH438_WRITE	=0X8A;
        public static final int USB_VEN_CH438_RESET	=0X8B;
        public static final int USB_VEN_READ_EEPROM	=0X8C;
        public static final int USB_VEN_WRITE_EEPROM	=0X8D;

    }
}
